package com.ares.comparer.config.errorHandler;

import com.ares.comparer.config.Result;
import de.redsix.pdfcompare.RenderingException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;


@ControllerAdvice
public class ErrorAdvice {

    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxSize;

    @ResponseBody
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    public Result maxUploadSizeExceptionAdvice(MaxUploadSizeExceededException e) {
        return Result.fail("上传文件不能大于" + maxSize);
    }

    @ResponseBody
    @ExceptionHandler(value = RenderingException.class)
    public Result outOfMemoryErrorExceptionAdvice(RenderingException e) {
        HashMap<String, Object> res = new HashMap<>();
        boolean isOutOfMemoryError = false;
        Throwable[] suppressedList = e.getSuppressed();
         for (Throwable suppressed : suppressedList) {
             Throwable cause1 = suppressed.getCause();
             if(cause1 == null) {
                 isOutOfMemoryError = suppressed.toString().contains("OutOfMemoryError");
             }else {
                 isOutOfMemoryError = cause1.toString().contains("OutOfMemoryError");
             }

             if(isOutOfMemoryError) {
                 break;
             }

         }
         if(isOutOfMemoryError) {
             res.put("suppressed", suppressedList);
             return Result.fail("文件过大导致系统内存不足, 请尝试减小文件尺寸!", res);
         }
        return Result.fail(e.getMessage());
    }
}
